package com.xdap.common.dao;

import com.definesys.mpaas.query.MpaasQuery;
import com.definesys.mpaas.query.MpaasQueryFactory;
import com.xdap.api.init.DatasourceService;
import com.xdap.api.moudle.formconfig.pojo.ListPageView;
import com.xdap.common.config.MongoDatasourceContainer;
import com.xdap.common.entity.XdapSessionEntity;
import com.xdap.common.session.XdapSession;
import com.xdap.fsapproval.module.pojo.XdapTenantDatabase;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @BelongsProject：IntelliJ IDEA
 * @BelongsPackage：com.adisseo.service.approval.dao
 * @Author：fei
 * @CreateTime：2022-09-08 09:48
 * @Description: 租户数据源相关查询
 * @Version：1.0
 */
@Repository
@RequiredArgsConstructor
public class TenantDatabaseDao {
    private final DatasourceService datasourceService;
    private final RuntimeDatasourceService runtimeDatasourceService;
    @Autowired
    private MongoDatasourceContainer mongoDatasourceContainer;
    @Autowired
    private MpaasQueryFactory mqf;

    private MpaasQuery buildQuery() {
        return runtimeDatasourceService.buildTenantNoSchemaMpaasQuery();
    }


//    @Autowired
//    MpaasQueryFactory sw;

    public XdapTenantDatabase getXdapTenantDatabase(String tenantId) {
        return datasourceService.buildTenantMpaasQuery("xdap_manage_database")
                .eq("tenant_id", tenantId)
                .table("xdap_tenant_database")
                .doQueryFirst(XdapTenantDatabase.class);
    }

    public String getTabId(String formId,String tenantId) {

        XdapSession.setXdapSession(XdapSessionEntity.builder()
                .mongoDatasource(this.mongoDatasourceContainer
                        .findMongoDatasource("mongoxdap_app_" + tenantId))
                .mysqlDatasource("xdap_app_" + tenantId).tenantId(tenantId).build());
        ListPageView listPageView = mqf.buildQuery(XdapSession.mongoDatasource(), "mongodb")
                //  .select("_id")
                .eq("formId", formId)
                .table("list_page_view").doQueryFirst(ListPageView.class);
        XdapSession.remove();
        String tabId = listPageView.getTabId();
        return tabId;

    }
}
